package com.shuwen.gcdj.service.basics;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuwen.gcdj.bean.DictResp;
import com.shuwen.gcdj.bean.basicsEquitment.request.FolderListReq;
import com.shuwen.gcdj.bean.basicsEquitment.response.FileDictResp;
import com.shuwen.gcdj.bean.basicsMaintenance.response.OrderFlowReq;
import com.shuwen.gcdj.bean.basicsMaintenance.response.OrderMainChildsResp;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.exception.ApiException;
import com.shuwen.gcdj.common.util.BeanHelper;
import com.shuwen.gcdj.entity.BasicsStructure;
import com.shuwen.gcdj.entity.SysDictionary;
import com.shuwen.gcdj.entity.basics.BasicsResource;
import com.shuwen.gcdj.entity.basics.OrderMaintenanceorderflow;
import com.shuwen.gcdj.mapper.mysql.BasicsStructureMapper;
import com.shuwen.gcdj.mapper.mysql.basics.BasicsResourceMapper;
import com.shuwen.gcdj.mapper.mysql.basics.OrderMaintenanceorderflowMapper;
import com.shuwen.gcdj.mapper.mysql.sysDictionary.SysDictionaryMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
public abstract class MethodFactory {

    @Resource
    private SysDictionaryMapper sysDictionaryMapper;

    @Resource
    private BasicsStructureMapper basicsStructureMapper;

    @Resource
    private OrderMaintenanceorderflowMapper orderMaintenanceorderflowMapper;

    @Resource
    private BasicsResourceMapper basicsResourceMapper;


    @Value("${savepath}")
    private String pathNamed;

    public static Boolean flag = true;

    public static Boolean getFlag() {
        return flag;
    }

    public static void setFlag(Boolean flag) {
        MethodFactory.flag = flag;
    }


    public String getPathNamed() {
        return pathNamed;
    }

    public void setPathNamed(String pathNamed) {
        this.pathNamed = pathNamed;
    }


    /**
     * 根据类型返回选项
     *
     * @param code
     * @return
     */
    public CommonResult<List<DictResp>> getType(String code) {
        List<SysDictionary> sysDictionaries = sysDictionaryMapper.selectList(new QueryWrapper<SysDictionary>().lambda()
                .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL)
                .eq(SysDictionary::getParentCode, code)
                .orderByDesc(SysDictionary::getCreateTime));
        List<DictResp> dictResps = BeanHelper.copyList(sysDictionaries, DictResp.class);
        return CommonResult.success(dictResps);
    }

    /**
     * 递归查询子集结构
     */
    public CommonResult<List<OrderMainChildsResp>> getRecursion(List<OrderMainChildsResp> basicsStructures) {
        List<OrderMainChildsResp> orderMainDetail = null;
        for (OrderMainChildsResp basicsStructure : basicsStructures) {
            List<BasicsStructure> basics = basicsStructureMapper.selectList(
                    new QueryWrapper<BasicsStructure>()
                            .lambda()
                            .eq(BasicsStructure::getParentId, basicsStructure.getId()));
            orderMainDetail = BeanHelper.copyList(basics, OrderMainChildsResp.class);
            basicsStructure.setChilds(orderMainDetail);
            if (!CollectionUtils.isEmpty(basics)) {
                this.getRecursion(orderMainDetail);
            }
        }
        return CommonResult.success(orderMainDetail);
    }


    /**
     * 保存维保流程
     */
    public void savaOrderFlow(OrderFlowReq req) {
        //维保流程新增
        OrderMaintenanceorderflow orderMaintenanceorderflow = new OrderMaintenanceorderflow();
        BeanUtils.copyProperties(req, orderMaintenanceorderflow);
        orderMaintenanceorderflowMapper.insert(orderMaintenanceorderflow);
    }

    /**
     * 递归查询所有文件
     */
    public List<FileDictResp> getFlow(List<FileDictResp> fileDictResp, FolderListReq req) {
        for (FileDictResp dictResp : fileDictResp) {
            Page<FileDictResp> page = new Page<>(req.getPageNum(), req.getPageSize(), true);
            IPage<FileDictResp> all = basicsResourceMapper.getAll(page, req, dictResp.getId());
            List<FileDictResp> records = all.getRecords();
            if (!CollectionUtils.isEmpty(records)) {
                dictResp.setChilds(records);
                this.getFlow(records, req);
            }
        }
        return fileDictResp;
    }

    /**
     * 递归只查询文件夹
     */
    public List<FileDictResp> getShu(List<FileDictResp> fileDictResp) {
        for (FileDictResp dictResp : fileDictResp) {
            List<FileDictResp> list = basicsResourceMapper.getList(dictResp.getId());
            if (!CollectionUtils.isEmpty(list)) {
                dictResp.setChilds(list);
                this.getShu(list);
            }
        }
        return fileDictResp;
    }

    /**
     * 递归根据id查询文件夹下所有
     */
    public List<Object> getFolder(FileDictResp fileDictResp, List<Object> list) {
        BasicsResource basicsResource = basicsResourceMapper.selectOne(
                new QueryWrapper<BasicsResource>().lambda()
                        .eq(BasicsResource::getIsFolder, true)
                        .eq(BasicsResource::getId, fileDictResp.getStoragePath()));
        if (!StringUtils.isEmpty(basicsResource)) {
            BeanUtils.copyProperties(basicsResource, fileDictResp);
            list.add(0, basicsResource);
            this.getFolder(fileDictResp, list);
        }
        return list;
    }


    /**
     * 创建文件夹
     *
     * @return
     */
    public void getpath(String id, List<String> path) throws UnsupportedEncodingException {
        String allPath = getAllPath(id, path);
        byte[] bytes = allPath.getBytes(StandardCharsets.UTF_8);
        File file = new File(new String(bytes, "UTF-8"));
        System.setProperty("sun.jnu.encoding", "utf-8");
        file.setWritable(true, true);
        file.mkdirs();
    }

    /**
     * 根据id查询父级路劲
     *
     * @param id
     * @param path
     * @return
     */
    public String getAllPath(String id, List<String> path) {
        String pathName = getPathNamed();
        if (StringUtils.isEmpty(id)) {
            return pathName;
        }
        BasicsResource basicsResource = basicsResourceMapper.selectOne(new QueryWrapper<BasicsResource>().lambda()
                .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL)
                .eq(BasicsResource::getId, id));
        if (StringUtils.isEmpty(basicsResource)) {
            throw new ApiException("数据有误");
        }
        if (!basicsResource.getStoragePath().equals(Constants.IS_HIDDEN_ALL)) {
            path.add(0, basicsResource.getPath());
            getAllPath(basicsResource.getStoragePath(), path);
        } else {
            path.add(0, basicsResource.getName());
        }
        for (String s : path) {
            pathName = pathName + "/" + s;
        }
        basicsResource.setPath(pathName);
        basicsResourceMapper.updateById(basicsResource);
        return pathName;
    }

    public Boolean getPath(List<String> ids, String id, String tagrtid) {
        List<BasicsResource> basicsResources = basicsResourceMapper.selectList(
                new QueryWrapper<BasicsResource>().lambda()
                        .eq(BasicsResource::getStoragePath, id)
                        .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL));
        if (!CollectionUtils.isEmpty(basicsResources)) {
            for (BasicsResource basicsResource : basicsResources) {
                if (basicsResource.getIsFolder()) {
                    ids.add(basicsResource.getId());
                    getPath(ids, basicsResource.getId(), tagrtid);
                }
            }
        }
        if (flag) {
            for (String s : ids) {
                if (s.equals(tagrtid)) {
                    return true;
                }
            }
            flag = false;
        }
        return false;
    }

    /**
     * 物理删除文件
     *
     * @param basicsResource
     */
    public void deleteFiles(BasicsResource basicsResource) {
        if (basicsResource.getIsFolder()) {
            List<BasicsResource> basicsResources = basicsResourceMapper.selectList(
                    new QueryWrapper<BasicsResource>().lambda()
                            .eq(BasicsResource::getIsDelete, Constants.IS_DELETE_NORMAL)
                            .eq(BasicsResource::getStoragePath, basicsResource.getId()));
            if (!CollectionUtils.isEmpty(basicsResources)) {
                for (BasicsResource resource : basicsResources) {
                    resource.setIsDelete(Constants.IS_DELETE_YES);
                    basicsResourceMapper.updateById(resource);
                    if (!resource.getIsFolder()) {
                        File filed = new File(resource.getPath());
                        filed.delete();
                    } else {
                        deleteFiles(resource);
                    }
                }
            }

            File fileped = new File(basicsResource.getPath());
            fileped.delete();
            basicsResource.setIsDelete(Constants.IS_DELETE_YES);
            basicsResourceMapper.updateById(basicsResource);
        } else {
            basicsResourceMapper.update(null, new UpdateWrapper<BasicsResource>().lambda()
                    .eq(BasicsResource::getId, basicsResource.getId())
                    .set(BasicsResource::getIsDelete, Constants.IS_DELETE_YES));
            File file = new File(basicsResource.getPath());
            file.delete();
        }
    }


    /**
     * 物理修改文件
     *
     * @param basicsResources
     */
    public void updateStopath(List<BasicsResource> basicsResources, List<String> list, BasicsResource now, BasicsResource parent) {
        String name = parent.getPath() + "/" + now.getName();
        String path = now.getPath();
        for (BasicsResource basicsResource : basicsResources) {
            List<BasicsResource> basicsResourcesed = basicsResourceMapper.selectList(
                    new QueryWrapper<BasicsResource>().lambda()
                            .eq(BasicsResource::getStoragePath, basicsResource.getId()));
            list.add(basicsResource.getId());
            if (!CollectionUtils.isEmpty(basicsResourcesed)) {
                updateStopath(basicsResourcesed, list, now, parent);
            }
        }
        if (flag) {
            for (String s : list) {
                BasicsResource basicsResource = basicsResourceMapper.selectById(s);
                String replace = basicsResource.getPath().replace(path, name);
                basicsResource.setPath(replace);
                basicsResourceMapper.updateById(basicsResource);
            }
            flag = false;
        }
    }

    /**
     * 修改子文件数据库真实路径
     *
     * @param basicsResource
     */
    public void updateCong(List<BasicsResource> basicsResource, List<String> list, String path, String lastPath) {
        for (BasicsResource resource : basicsResource) {
            BasicsResource basics = basicsResourceMapper.selectById(resource.getId());
            String name = lastPath;
            String pathing = path;
            List<BasicsResource> basicsResources = basicsResourceMapper.selectList(
                    new QueryWrapper<BasicsResource>().lambda().eq(BasicsResource::getStoragePath, basics.getId()));
            for (BasicsResource basicsResourcing : basicsResources) {
                List<BasicsResource> basicsResourcesed = basicsResourceMapper.selectList(
                        new QueryWrapper<BasicsResource>().lambda()
                                .eq(BasicsResource::getStoragePath, basicsResourcing.getId()));
                list.add(basicsResourcing.getId());
                if (!CollectionUtils.isEmpty(basicsResourcesed)) {
                    updateCong(basicsResourcesed, list, path, lastPath);
                }
            }

            if (flag) {
                for (String s : list) {
                    BasicsResource now = basicsResourceMapper.selectById(s);
                    String replace = now.getPath().replace(name, pathing);
                    now.setPath(replace);
                    basicsResourceMapper.updateById(now);
                }
                flag = false;
            }
        }

    }


}
